package com.qfedu.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qfedu.dao.PetsDao;
import com.qfedu.dto.PetsAndUser;
import com.qfedu.entity.Pets;
import com.qfedu.service.intf.PetsService;
import com.qfedu.vo.PageVo;
import com.qfedu.vo.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Service
public class PetsServiceImpl implements PetsService {
    @Resource
    PetsDao petsDao;

    @Override
    public R add(Pets pets) {
        if (petsDao.add(pets) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }

    @Override
    public R del(int id) {
        if (petsDao.del(id) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }

    @Override
    public R update(Pets pets) {
        if (petsDao.update(pets) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }

    @Override
    public PageVo queryPage(int page, int limit, PetsAndUser petsAndUser) {
        PageHelper.startPage(page, limit);
        PageInfo<PetsAndUser> petsPageInfo = new PageInfo<>(petsDao.all(petsAndUser));
        return PageVo.ok(petsPageInfo.getTotal(), petsPageInfo.getList());
    }

    @Override
    public void exportData(HttpServletResponse response) throws IOException {
        //1.设置下载的文件名
        String fn = "pets-" + System.currentTimeMillis() + ".txt";
        //2.设置下载的响应消息头 固定
        response.setHeader("content-disposition", "attachment;filename=" + fn);
        response.setCharacterEncoding("UTF-8");
        //3.查询下载的数据
        List<PetsAndUser> lists = petsDao.all(null);
        //4.IO流写出

        PrintWriter pw = response.getWriter();
        for (PetsAndUser f : lists) {
            pw.println(f.toString());
        }
        pw.flush();
    }
}
